﻿using System;
using System.IO;
using System.Text;

namespace UFrame.NetSocket
{
    public class ProtoBufNetSerialiser : IPacketSerialiser
    {
        private readonly ObjectPool<MemoryStream> memoryStreamObjectPool;

        public ProtoBufNetSerialiser()
        {
            memoryStreamObjectPool = new ObjectPool<MemoryStream>(0,1,()=>new MemoryStream());
        }

        public byte[] Serialize<T>(T packet)
        {
            var memoryStream = memoryStreamObjectPool.Allocate();
#if USE_PROTOBUF
            memoryStream.SetLength(0);
            ProtoBuf.Serializer.Serialize(memoryStream, packet);
#endif
            var packetBytes = memoryStream.ToArray();
            memoryStreamObjectPool.Release(memoryStream);
            return packetBytes;
        }

        public T Deserialise<T>(byte[] packetBytes, int offset, int length)
        {
#if USE_PROTOBUF
            //UnityEngine.Debug.LogError("Deserialise offset:" + 0 + "length:" + length);
            //var memoryStream = memoryStreamObjectPool.Allocate();
            //memoryStream.SetLength(length + 1);
            //memoryStream.Seek(0, SeekOrigin.Begin);
            //memoryStream.Write(packetBytes, offset, length);
            //var deserialised = ProtoBuf.Serializer.Deserialize<T>(memoryStream);
            //memoryStreamObjectPool.Release(memoryStream);
            T deserialised;
            using (var memoryStream = new MemoryStream(packetBytes, offset, length))
            {
                deserialised = ProtoBuf.Serializer.Deserialize<T>(memoryStream);
            }
            return deserialised;
#else
            UnityEngine.Debug.LogError("USE_PROTOBUF not define!");
            return default(T);
#endif
        }

    }
}
